<?php
namespace app\common\controller;

use think\Controller;
use think\controller\Rest;
use think\Db;
use think\Request;

class RestBase extends Rest 
{
    /**
     * @var null 服务名称  可在子类重载，若子类没有重载，则不会自动创建服务对象
     */
    protected $serviceName = null;
    /**
     * @var \app\common\service\Service
     */
    protected $service = null;
    
    public function __construct()
    {
        parent::__construct();
        //黑名单监测
        $this->checkBlackHost();
        $this->initService();
    }


    /**
     *黑名单监测
     */
    private function checkBlackHost(){
        $black_host=config('black_host');
        $request = Request::instance();
        if(in_array($request->domain(),$black_host )){
            log_debug("非法域名访问", $request->domain());
            $this->ajaxReturn(error("非法域名访问!"));
        }
        if(in_array($request->ip(),$black_host )){
            log_debug("非法IP访问", $request->ip());
            $this->ajaxReturn(error("非法Ip访问!"));
        }

    }

    /**
     * 设置服务
     * @param null $serciceName
     */
    public function setService($serciceName = null)
    {
        $this->serviceName = $serciceName;
    }

    /**
     * 初始化服务
     */
    protected function initService()
    {
        if ($this->serviceName) {
            $this->service = service($this->serviceName);
        }
    }

   
    /**
     * 显示结果
     * @param $res
     * @param bool $isajax
     * @param bool $isexit
     */
    protected function showResult($res, $isajax = true,$isexit=true)
    {
        if($isajax){
            return $this->response($res);
        }else{
            dump($res);
            if($isexit){
                exit();
            }
            
        }
    }

    
    /**
     * ajax返回数据
     * @param $res
     * @param bool $isexit
     */
    protected function ajaxReturn($res,$isexit=true)
    {
        echo json_encode($res);
        if($isexit){
            exit();
        }
    }

    /**
     * 输出日志
     */
    protected function log($key, $content, $type = 1)
    {
        $logService = new \app\common\service\Log();
        return $logService->log($key, $content, $type);
    }

    /**
     * 信息日志
     */
    public function infoLog($key, $content)
    {
        return $this->log($key, $content, 1);
    }

    /**
     * 错误日志
     */
    public function errorLog($key, $content)
    {
        return $this->log($key, $content, 3);
    }

    /**
     * 调试日志
     */
    public function debugLog($key, $content)
    {
        return $this->log($key, $content, 2);
    }
}
